package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.system.domain.SuperOrderAddress;
import com.ruoyi.system.domain.SuperOrderItem;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.SuperCartItemMapper;
import com.ruoyi.system.mapper.SuperOrderAddressMapper;
import com.ruoyi.system.mapper.SuperOrderItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SuperOrdersMapper;
import com.ruoyi.system.domain.SuperOrders;
import com.ruoyi.system.service.ISuperOrdersService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-14
 */
@Service
public class SuperOrdersServiceImpl implements ISuperOrdersService 
{
    @Autowired
    private SuperOrdersMapper superOrdersMapper;
    @Resource
    private SuperOrderItemMapper superOrderItemMapper;
    @Resource
    private SuperCartItemMapper superCartItemMapper;
    @Resource
    private SuperOrderAddressMapper superOrderAddressMapper;

    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public SuperOrders selectSuperOrdersById(Long id)
    {
        return superOrdersMapper.selectSuperOrdersById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param superOrders 订单
     * @return 订单
     */
    @Override
    public List<SuperOrders> selectSuperOrdersList(SuperOrders superOrders)
    {
        return superOrdersMapper.selectSuperOrdersList(superOrders);
    }

    /**
     * 新增订单
     * 
     * @param superOrders 订单
     * @return 结果
     */
    @Override
    public int insertSuperOrders(SuperOrders superOrders)
    {
        return superOrdersMapper.insertSuperOrders(superOrders);
    }

    /**
     * 修改订单
     * 
     * @param superOrders 订单
     * @return 结果
     */
    @Override
    public int updateSuperOrders(SuperOrders superOrders)
    {
        SuperOrders superOrders1 = superOrdersMapper.selectSuperOrdersById(superOrders.getId());
        // 3是待评价
        superOrders1.setStatus(3);
        return superOrdersMapper.updateSuperOrders(superOrders1);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteSuperOrdersByIds(Long[] ids)
    {
        return superOrdersMapper.deleteSuperOrdersByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteSuperOrdersById(Long id)
    {
        return superOrdersMapper.deleteSuperOrdersById(id);
    }

    // 添加订单 并往订单明细表添加数据
    @Override
    @Transactional
    public Long myAdd(OrderVo order) {
        List<CartVo> cartVos = order.getOrder();// 订单详细
        Boolean flag = order.getFlag(); // 配送方式 true 为配送方式  false 为自提
        Long addressId = order.getAddressId(); // 收货地址id
        String remark = order.getRemark();

        // 首先往订单表添加数据
        SuperOrders superOrders = new SuperOrders();
        Long userId = cartVos.get(0).getUserId();
        Long payId = 0L;
        Long deliveryId = 0L;
        if(!flag){
            deliveryId=1L;
        }
        Date createAt = new Date();
        Date updatedAt = new Date();
        Integer status = 0;
        Integer del = 0;
        BigDecimal totalAmount = new BigDecimal(0);

        for (CartVo cartVo : cartVos) {
            // 获取商品单价和数量
            BigDecimal price = cartVo.getProduct().getPrice();
            Long quantity = cartVo.getQuantity(); // 数量
            // 计算当前商品的总价：单价 * 数量
            BigDecimal itemTotal = price.multiply(new BigDecimal(quantity));
            totalAmount = totalAmount.add(itemTotal);
        }
        superOrders.setUserId(userId);
        superOrders.setPayId(payId);
        superOrders.setDeliveryId(deliveryId);
        superOrders.setTotalAmount(totalAmount);
        superOrders.setStatus(status);
        superOrders.setCreateAt(createAt);
        superOrders.setUpdatedAt(updatedAt);
        superOrders.setRemark(remark);
        superOrders.setDel(del);
        int i = superOrdersMapper.insertSuperOrders(superOrders);
        Long id = superOrders.getId();
        // 然后往订单明细表添加数据
        for(CartVo cartVo : cartVos){
            SuperOrderItem item = new SuperOrderItem();
            item.setOrderId(id);
            item.setProductId(cartVo.getProductId());
            item.setProductName(cartVo.getProduct().getName());
            item.setQuantity(cartVo.getQuantity());
            item.setUnitPrice(cartVo.getProduct().getPrice());
            BigDecimal price = cartVo.getProduct().getPrice();
            price = price.multiply(new BigDecimal(cartVo.getQuantity())); // 总价
            item.setSubtotal(price);
            item.setDel(0L);
            i*=superOrderItemMapper.insertSuperOrderItem(item);
        }

        // 最后从购物车表删除数据
        for(CartVo cartVo : cartVos){
            i*=superCartItemMapper.deleteSuperCartItemById(cartVo.getId());
        }

        // 往订单地址表里面添加数据
        // 需要订单id   id
        // 地址id    addressId
        SuperOrderAddress address = new SuperOrderAddress();
        address.setOrderId( id);
        address.setAddressId(addressId);
        i*=superOrderAddressMapper.insertSuperOrderAddress(address);
        if(i==0){
            throw new RuntimeException("添加订单失败");
        }
        return id;
    }

    @Override
    // 直接购买商品订单
    @Transactional
    public Long isProductOrder(IsProductOrderVo isProductOrder) {
        // 首先在订单表填加数据获取订单id
        SuperOrders orders = new SuperOrders();
        orders.setUserId(isProductOrder.getUserId());
        // 新增订单没有支付 0
        orders.setPayId(0L);
        // 配送方式
        orders.setDeliveryId(isProductOrder.getDeliverId());
        orders.setTotalAmount(isProductOrder.getTotalAmount());
        orders.setStatus(0);
        orders.setCreateAt(new Date());
        orders.setUpdatedAt(new Date());
        // 备注
        orders.setRemark(isProductOrder.getRemark());
        orders.setDel(0);
        int i = superOrdersMapper.insertSuperOrders(orders);

        Long id = orders.getId(); // 订单id

        // 订单详情表添加数据
        SuperOrderItem item = new SuperOrderItem();
        item.setOrderId(id);
        item.setProductId(isProductOrder.getProductId());
        item.setProductName(isProductOrder.getProductName());
        item.setQuantity(isProductOrder.getQuantity());
        item.setUnitPrice(isProductOrder.getUnitPrice());
        item.setSubtotal(isProductOrder.getUnitPrice()); // 单个购买商品小计为单价
        item.setDel(0L);
        i*=superOrderItemMapper.insertSuperOrderItem(item);

        // 订单地址表添加数据
        SuperOrderAddress address = new SuperOrderAddress();
        address.setOrderId(id);
        address.setAddressId(isProductOrder.getAddressId());
        i*=superOrderAddressMapper.insertSuperOrderAddress(address);


        if(i>0){
            return id;
        }
        throw new RuntimeException("添加订单失败");
    }

    @Override
    // 查看用户付款后的自提订单
    public List<SelfOrderVo> selfOrder(Long userId) {
        // 订单表查询，用户userId 的所有支付后的订单信息
        List<SelfOrderVo> seledOrder = superOrdersMapper.seleOrder(userId);
        return seledOrder;
    }

    @Override
    // 查看用户付款后的自提订单详情
    public List<SelfDetailVo> selfOrderDetail(Long id) {
        return superOrdersMapper.selfOrderDetail(id);
    }

    @Override
    // 查看用户付款后的自提订单地址
    public SelfAddressVo selfAddress(Long id) {
        return superOrdersMapper.selfAddress(id);
    }

    @Override
    public Map<String, Object> getTime(Long id) {
        return superOrdersMapper.getTime(id);
    }
}
